package com.atguigu.gulimall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @title: GuliFeignConfig
 * @Author syh
 * @Date: 2022/7/12 21:07
 * @Version 1.0
 */

@Configuration
public class GuliFeignConfig {

    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {

            @Override
            public void apply(RequestTemplate template) {
                // 1.使用RequestContextHolder这个对象可以获取到当前所有的请求属性,spring将其放到了当前线程中
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (requestAttributes != null) {
                    HttpServletRequest request = requestAttributes.getRequest();
                    // 同步请求头信息,可以获取到页面的cookie数据
                    // 获取页面中的cookie信息
                    if (request != null) {
                        String cookie = request.getHeader("Cookie");
                        // 放置到新请求中,相当于给模拟的http请求中设置了cookie信息
                        template.header("Cookie", cookie);
                    }
                }
            }
        };
    }
}
